
#include "xdns-server-manager-impl.h"
#include "xdns-server-selector.h"
#include <assert.h>

using namespace std;

XdnsServerManager::XdnsServerManager()
: m_listeners()
{
}

XdnsServerManager::~XdnsServerManager()
{
}

XdnsError
XdnsServerManager::Init(vector<XdnsServerState*>& serverStates,
                        XdnsServerManager** serverManager)
{
    if ((serverStates.empty()) ||
        (NULL == serverManager))
    {
        return XE_Inval;
    }

    // Check if any pointer to the server state is NULL.
    vector<XdnsServerState*>::iterator iter = serverStates.begin();
    vector<XdnsServerState*>::iterator end = serverStates.end();
    for (; iter != end; ++iter)
    {
        if (NULL == (*iter))
        {
            return XE_Inval;
        }
    }

    // Initialize a server selector.
    XdnsServerSelector* selector = NULL;
    XdnsError error = XdnsServerSelector::Init(serverStates,
                                               &selector);
    if (error != XE_Ok)
    {
        return error;
    }

    /* Create a new server manager and it takes the ownership of the
       server selector and states.
    */
    XdnsServerManagerImpl* serverManagerImpl = new (nothrow) XdnsServerManagerImpl(serverStates,
                                                                                   selector);
    if (NULL == serverManagerImpl)
    {
        XdnsServerSelector::Release(selector);
        return XE_NoMem;
    }

    *serverManager = serverManagerImpl;
    return XE_Ok;
}

void
XdnsServerManager::Release(XdnsServerManager* serverManager)
{
    if (serverManager != NULL)
    {
        delete serverManager;
    }
}

void
XdnsServerManager::RegisterListener(XdnsServerManagerListener& listener)
{
    m_listeners.insert(&listener);
}

void
XdnsServerManager::UnregisterListener(XdnsServerManagerListener& listener)
{
    m_listeners.erase(&listener);
}

void
XdnsServerManager::NotifyListeners(long queryId,
                                   XdnsError error,
                                   const XdnsData* data,
                                   size_t startOffset,
                                   const XdnsHeaderInfo* header)
{
    set<XdnsServerManagerListener*>::iterator iter = m_listeners.begin();
    set<XdnsServerManagerListener*>::iterator end = m_listeners.end();
    for (; iter != end; ++iter)
    {
        XdnsServerManagerListener* listener = *iter;
        assert(listener != NULL);
        listener->ReplyReceived(queryId, error, data, startOffset, header);
    }
}

